<template>
  <div class="container">
    <div class="header-box">
      <van-nav-bar
          title="订单详情"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
      />
    </div>
    <div class="order-info">
      <van-form @submit="onSubmit">
        <div
            class="form-item"
            v-for="(item, index) in orderFormItems"
            :key="index"
        >
          <p>
            <span>{{ item.label }}</span>
            <span class="label-en">{{ item.enLabel }}</span>
          </p>
          <van-field
              :readonly="item.readonly"
              :disabled="item.disabled"
              v-model="orderInfo[item.name]"
              :name="item.name"
              autocomplete="off"
              @click="selectInput(item.name)"
          />
        </div>
        <div class="print-btn">
          <van-row>
            <van-col span="8">
              <van-button
                  size="large"
                  type="primary"
                  @click="print"
                  native-type="button"
              >打印订单
              </van-button
              >
            </van-col>
            <van-col span="8">
              <van-button
                  size="large"
                  type="warning"
                  @click="printWarehousing"
                  native-type="button"
              >打印包裹单
              </van-button
              >
            </van-col>
            <van-col span="8">
              <van-button type="info" size="large" native-type="submit"
              >更新订单
              </van-button
              >
            </van-col>
          </van-row>
        </div>
      </van-form>
      <!-- 日期选择器 -->
      <van-popup v-model="dateShow" position="bottom">
        <van-datetime-picker
            @confirm="selectDataVal"
            @cancel="dateShow = false"
            v-model="currentDate"
            type="datetime"
            title="选择年月日"
        />
      </van-popup>
      <van-popup
          v-model="printGoodsShow"
          :style="{ height: '100%' }"
          position="bottom"
      >
        <div class="print-box">
          <div class="print-form">
            <van-field
                label="订单编号"
                :readonly="true"
                v-model="goodsOrder.orderNo"
                name="orderNo"
                autocomplete="off"
            />
            <van-field
                label="进仓日期"
                :readonly="true"
                v-model="goodsOrder.warehousingTime"
                name="orderNo"
                autocomplete="off"
            />
            <van-field
                label="客户名称"
                v-model="goodsOrder.customerName"
                name="orderNo"
                autocomplete="off"
            />
            <van-field
                label="包裹名称"
                v-model="goodsOrder.packageName"
                name="orderNo"
                placeholder="请输入包裹名称"
                autocomplete="off"
            />
            <van-field
                label="包裹内容"
                v-model="goodsOrder.packageContent"
                name="orderNo"
                placeholder="请输入包裹内容"
                autocomplete="off"
            />
            <van-field
                label="包裹数量"
                type="number"
                v-model="goodsOrder.packageNum"
                name="orderNo"
                placeholder="请输入包裹数量"
                autocomplete="off"
            />
            <van-field
                label="总件数量"
                type="number"
                v-model="goodsOrder.total"
                name="orderNo"
                placeholder="请输入总件数量"
                autocomplete="off"
            />
            <van-field
                label="存放区号"
                v-model="goodsOrder.area"
                name="orderNo"
                placeholder="请输入存放区号"
                autocomplete="off"
            />
            <van-field name="radio" label="打包类型">
              <template #input>
                <van-radio-group
                    v-model="goodsOrder.baleType"
                    direction="horizontal"
                >
                  <van-radio name="压缩">压缩</van-radio>
                  <van-radio name="手打">手打</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field
                label="打包数量"
                type="number"
                v-model="goodsOrder.baleNum"
                name="orderNo"
                placeholder="请输入打包数量"
                autocomplete="off"
            />
            <van-field
                v-model="goodsOrder.baleRemark"
                rows="2"
                autosize
                label="打包备注"
                type="textarea"
                maxlength="100"
                placeholder="请输入打包备注"
                show-word-limit
            />
          </div>
          <div class="print-bottom">
            <van-row>
              <van-col span="12">
                <van-button
                    type="default"
                    block
                    @click="printGoodsShow = false"
                >
                  退出
                </van-button>
              </van-col>
              <van-col span="12">
                <van-button type="info" block @click="storehousePrint"
                >打印包裹单
                </van-button
                >
              </van-col>
            </van-row>
          </div>
        </div>
      </van-popup>
      <!-- 页面加载 -->
      <div class="page-loading" v-if="pageLoading">
        <van-loading color="#1989fa" text-color="#1989fa" vertical>
          加载中...
        </van-loading>
      </div>
      <van-field
          readonly
          clickable
          label="选择打印机"
          :value="printerDeviceId"
          placeholder="选择打印机"
          @click="showPrinterPicker = true"
      />
      <van-popup v-model="showPrinterPicker" round position="bottom">
        <van-picker
            show-toolbar
            value-key="label"
            :columns="printerList"
            @cancel="showPrinterPicker = false"
            @confirm="onConfirm"
        />
      </van-popup>
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from "vue-property-decorator";
import {List, Search, Dialog, Toast} from "vant";
import {orderInfo, printOrder, editOrder, printPackage} from "@/api/manager";
import tools from "@/utils/tools";
import {findPrinterList} from "@/api/system";

@Component({
  components: {
    List,
    Search,
    Dialog,
  },
})
export default class ManagerIndex extends Vue {
  // 订单id
  orderNo: any = this.$route.query.orderNo;
  // 页面加载
  pageLoading = false;
  // 打印货单窗口
  printGoodsShow = false;
  // 日期显示
  dateShow = false;
  currentDate: any = null;
  // 订单详情表单
  orderFormItems: any = [
    {
      name: "orderno",
      label: "订单编号",
      enLabel: "Order No",
      readonly: true,
      disabled: false,
    },
    {
      name: "customerName",
      label: "客户名称",
      enLabel: "Customer's name",
      readonly: true,
      disabled: true,
    },
    {
      name: "customerCode",
      label: "客户代码",
      enLabel: "Customer's code",
      readonly: true,
      disabled: true,
    },
    {
      name: "customerPhone",
      label: "客户电话",
      enLabel: "Customer's phone",
      readonly: true,
      disabled: true,
    },
    {
      name: "nationalityName",
      label: "客户国籍",
      enLabel: "Customer's nationality",
      readonly: true,
      disabled: true,
    },
    {
      name: "goodsName",
      label: "货物名称",
      enLabel: "Cargo name",
      readonly: false,
      disabled: false,
    },
    {
      name: "packageQuantity",
      label: "包装数量",
      enLabel: "Package Quantity",
      readonly: false,
      disabled: false,
    },
    {
      name: "goodsQuantity",
      label: "货物总数量",
      enLabel: "Cargo Quantity",
      readonly: false,
      disabled: false,
    },
    {
      name: "goodsSize",
      label: "货物体积",
      enLabel: "Cargo Volume",
      readonly: false,
      disabled: false,
    },
    {
      name: "storageArea",
      label: "存放区号",
      enLabel: "Storage area number",
      readonly: false,
      disabled: false,
    },
    {
      name: "warehousingTime",
      label: "入仓时间",
      enLabel: "Date of entry into warehouse",
      readonly: true,
      disabled: false,
    },
    {
      name: "sellerPhone",
      label: "档口电话",
      enLabel: "Stall phone",
      readonly: false,
      disabled: false,
    },
    {
      name: "sellerAddress",
      label: "档口地址",
      enLabel: "Stall address",
      readonly: false,
      disabled: false,
    },
    {
      name: "companyName",
      label: "公司名称",
      enLabel: "Logistics company name",
      readonly: true,
      disabled: true,
    },
    {
      name: "companyPhone",
      label: "公司电话",
      enLabel: "Logistics company phone",
      readonly: true,
      disabled: true,
    },
    {
      name: "companyAddress",
      label: "公司地址",
      enLabel: "Logistics company address",
      readonly: true,
      disabled: true,
    },
  ];
  // 订单详情
  orderInfo: any = {
    id: null,
    orderno: null,
    customerName: null,
    customerCode: null,
    customerPhone: null,
    customerNationality: null,
    goodsName: null,
    goodsQuantity: null,
    packageQuantity: null,
    goodsSize: null,
    storageArea: null,
    sellerPhone: null,
    sellerAddress: null,
    warehousingTime: null,
    companyId: null,
    companyPhone: null,
    companyAddress: null,
  };
  // 打印货单字段
  goodsOrder: any = {
    orderNo: "",
    warehousingTime: "",
    customerName: "",
    packageName: "",
    packageContent: "",
    packageNum: "",
    total: "",
    area: "",
    baleType: "压缩",
    baleNum: "",
    baleRemark: "",
  };
  // 打印机id
  printerList: any = [];
  showPrinterPicker = false;
  printerDeviceId: number = 0;
  // 1.打印订单 2.打印包裹
  printerType: number = 1;

  // 日期选择器
  selectInput(name: any) {
    if (name == "warehousingTime") {
      this.currentDate = new Date(
          this.orderInfo.warehousingTime.replace(/-g/, "/")
      );
      this.dateShow = true;
    }
  }

  selectDataVal(val: any): void {
    this.orderInfo.warehousingTime = tools.formatDate(val, "yyyy-MM-dd HH:mm");
    this.dateShow = false;
  }

  // 生命钩子
  async created(): Promise<void> {
    try {
      this.pageLoading = true;
      await this.getOrderInfo();
      this.pageLoading = false;
    } catch (e) {
      this.pageLoading = false;
    }
  }

  // 获取订单详情
  async getOrderInfo(): Promise<void> {
    this.orderInfo = (await orderInfo(this.orderNo)).data;
  }

  // 打印订单
  async print(): Promise<void> {
    this.printerType = 1
    this.showPrinterPicker = true;
    await this.getPrinterList()
    // if (!this.orderInfo.id) {
    //   Toast("订单不存在");
    //   return;
    // }
    // Dialog.alert({
    //   message: "是否需要打印订单？",
    //   showCancelButton: true,
    // }).then(async () => {
    //   try {
    //     printOrder([this.orderInfo.id])
    //       .then((res) => {
    //         Toast((res as any).msg);
    //       })
    //       .catch((e) => {
    //         Toast("打印失败");
    //       });
    //   } catch (e: any) {
    //     Toast(e);
    //   }
    // });
  }

  // 打印仓库单
  printWarehousing(): void {
    this.goodsOrder.orderNo = this.orderInfo.orderno;
    this.goodsOrder.packageContent = this.orderInfo.goodsName;
    this.goodsOrder.packageNum = this.orderInfo.packageQuantity;
    this.goodsOrder.total = this.orderInfo.goodsQuantity;
    this.goodsOrder.warehousingTime = this.orderInfo.warehousingTime;
    this.goodsOrder.customerName = this.orderInfo.customerName;
    this.goodsOrder.area = this.orderInfo.storageArea;
    this.printGoodsShow = true;
  }

  async storehousePrint(): Promise<void> {
    this.printerType = 2
    this.showPrinterPicker = true;
    await this.getPrinterList()
    // Dialog.alert({
    //   message: "是否打印包裹单？",
    //   showCancelButton: true,
    // }).then(async () => {
    //   try {
    //     printPackage(this.goodsOrder).then((res: any) => {
    //       Toast(res.msg);
    //       this.showPrinterPicker = false;
    //     });
    //   } catch (e: any) {
    //     Toast(e);
    //   }
    // });
  }

  // 提交修改
  onSubmit(): void {
    Dialog.alert({
      message: "是否更新订单",
      showCancelButton: true,
    }).then(async () => {
      try {
        this.pageLoading = true;
        await editOrder(this.orderInfo);
        Toast("更新成功");
        this.pageLoading = false;
      } catch (e) {
        this.pageLoading = false;
      }
    });
  }

  // 返回
  onClickLeft(): void {
    this.$router.go(-1);
  }

  onConfirm(item: any): void {
    let postData = {}
    this.pageLoading = true
    if (this.printerType == 1) {
      postData = {
        orderIds: [this.orderInfo.id],
        printerDeviceId: item.value
      }
      printOrder(postData).then((res: any) => {
        Toast((res as any).msg)
        this.showPrinterPicker = false;
      }).finally(() => {
        this.pageLoading = false
      })
    }
    if (this.printerType == 2) {
      postData = {
        ...this.goodsOrder,
        printerDeviceId: item.value
      }
      printPackage(postData).then((res: any) => {
        Toast(res.msg);
        this.showPrinterPicker = false;
      }).finally(() => {
        this.pageLoading = false
      })
    }
  }

  // 获取打印机列表
  async getPrinterList(): Promise<void> {
    this.pageLoading = true
    try {
      const res = await findPrinterList()
      this.printerList = res.data
      this.pageLoading = false
    } catch (e: any) {
      this.pageLoading = false
      Toast(e?.message || "获取打印机列表失败")
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  overflow-y: hidden;

  .header-box {
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 99;
  }

  .order-info {
    width: 100%;
    margin-top: 46px;
    overflow-y: auto;
    height: calc(100% / 1 - 46px);
    box-sizing: border-box;
    padding-bottom: 50px;

    .form-item {
      padding-top: 5px;
      border-bottom: 1px #f5f5f5 solid;

      p {
        margin-left: 16px;
        font-size: 18px;
        line-height: 22px;

        span {
          display: block;
        }

        .label-en {
          font-weight: 600;
          font-size: 15px;
        }
      }

      ::v-deep .van-field__control {
        font-size: 16px !important;
      }
    }
  }

  .print-btn {
    width: 100%;
    height: 50px;
    bottom: 0;
    position: absolute;

    .van-button {
      border-radius: 0 !important;
    }
  }

  .page-loading {
    position: fixed;
    top: 0;
    z-index: 99;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.3);
  }

  .print-box {
    position: relative;

    .print-form {
      margin-bottom: 55px;
    }

    .van-cell {
      padding: 15px 16px;
      font-size: 16px !important;
    }

    .print-bottom {
      width: 100%;
      height: 55px;
      position: fixed;
      bottom: 0;
      box-sizing: border-box;
      border-bottom: 0;

      .van-button {
        font-size: 15px;
        height: 55px !important;
        border-radius: 0 !important;
      }
    }
  }
}
</style>
